/*
 * @lc app=leetcode.cn id=1160 lang=javascript
 *
 * [1160] 拼写单词
 */

// @lc code=start
var getMap = function (word) {
  const map = {};
  word.split('').forEach(ch => {
    map[ch] = map[ch] ? map[ch] + 1 : 1;
  });
  return map;
}
/**
 * @param {string[]} words
 * @param {string} chars
 * @return {number}
 */
var countCharacters = function (words, chars) {
  const map = getMap(chars);
  return words
    .filter(word => {
      return Object.entries(getMap(word))
        .filter(([ch, num]) => {
          return map[ch] === undefined || num > map[ch];
        }).length === 0;
    })
    .reduce((pre, cur) => pre + cur.length, 0);
};
// @lc code=end
